/**
 * 深度优先搜索查找树节点
 * @param tree 树形结构数组
 * @param targetId 目标节点id
 * @param idKey 节点id的key
 * @param targetType 目标节点的类型或路径
 * @returns 找到的节点和其父节点
 */
export function findNodeByDFS(tree, targetId, idKey = "id", targetType = "moulds") {
  const dfs = (nodes, parent) => {
    for (const node of nodes) {
      // 先检查 moulds 数组
      if (node[targetType] && Array.isArray(node[targetType])) {
        const found = node[targetType].find(item => item[idKey] === targetId);
        if (found) {
          return { node: found, parent: node };
        }
      }

      // 如果有子节点，继续深入搜索
      if (node.children) {
        const result = dfs(node.children, node);
        if (result.node) {
          return result;
        }
      }
    }
    return { node: null, parent: null };
  };

  return dfs(tree);
}

/**
 * 广度优先搜索查找树节点
 * @param tree 树形结构数组
 * @param targetId 目标节点id
 * @param children 子节点的属性名
 * @param idKey id的属性名
 * @param targetType 目标节点的类型或路径，用于在有重复id时确定正确的节点
 * @returns 找到的节点和其父节点
 */
export function findNodeByBFS(
  tree,
  targetId,
  children = "children",
  idKey = "id",
  targetType = "moulds"
) {
  const queue = tree.map((node) => ({
    node,
    parent: null,
  }));
  console.log('===> queue', queue)
  while (queue.length > 0) {
    const { node, parent } = queue.shift();
    // 检查当前节点的子节点数组（比如 moulds）中是否存在目标 id
    if (node[targetType] && Array.isArray(node[targetType])) {
      const found = node[targetType].find(item => item[idKey] === targetId);
      console.log('===> found', found)
      if (found) {
        return { node: found, parent: node };
      }
    }

    // 如果当前节点就是目标节点
    if (node[idKey] === targetId) {
      return { node, parent };
    }

    // 将子节点加入队列
    if (node[children]) {
      queue.push(
        ...node[children].map((child) => ({
          node: child,
          parent: node,
        })),
      );
    }
  }
  
  return { node: null, parent: null };
}
